package win.devhu.testing.simple

import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.MultiFormatReader
import com.google.zxing.client.j2se.BufferedImageLuminanceSource
import com.google.zxing.client.j2se.MatrixToImageWriter
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.qrcode.QRCodeWriter
import java.io.File
import java.nio.file.FileSystems
import javax.imageio.ImageIO


fun main(args:Array<String>){
    val fileName:String = "tmp/QRCode.png"
    val content:String = "胡予"
    encodeQR(content, fileName)
    decodeQR(fileName)
}

//创建二维码
fun encodeQR(content: String,filename:String){
    val qrCodeWriter = QRCodeWriter()
    //new String(content.getBytes("UTF-8"), "ISO-8859-1");  JAVA 这样操作
    val contentUtf8 = String(content.toByteArray(charset("UTF-8")), charset("ISO-8859-1"))    //解决中文乱码问题
    val bitMatrix = qrCodeWriter.encode(
            contentUtf8,
            BarcodeFormat.QR_CODE,
            350,350)

    val path = FileSystems.getDefault().getPath(filename)
    MatrixToImageWriter.writeToPath(bitMatrix,"PNG",path)
}

//二维码解析
fun decodeQR(filename: String){
    val QRfile = File(filename)
    val bufferedImg = ImageIO.read(QRfile)
    val source = BufferedImageLuminanceSource(bufferedImg)
    val bitmap = BinaryBitmap(HybridBinarizer(source))

    val result = MultiFormatReader().decode(bitmap)
    println("Barcode Format: " + result.getBarcodeFormat())
    println("Content: " + result.getText())
}
